<?php

namespace app\api\service;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\api\controller\Auth;
use app\api\model\AdminModel;
use app\api\model\AuthModel;
use app\api\model\TeamModel;
use fast\Random;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class AdminService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 获取等级账号
     */
    public function getAdminLevelList($params)
    {
        $adminIds = self::getAdminIds();
        $adminList = AdminModel::getInstance()->select([
            'id' => ['in', $adminIds]
        ], 'id,username,nickname,level,pid,team', 0, 1000000);
        $teamList = Db::name('team')->where([
            'id' => ['in', array_column($adminList, 'team')]
        ])->column('title', 'id');
        $level = [];
        foreach ($adminList as $k => $v)
        {
            $level[$v['level']]['levelId'] = $v['level'];
            $level[$v['level']]['levelName'] = str_replace('元', '', IdentityService::getInstance()->num_to_rmb($v['level'], 'c2')).'级';
            $v['teamTitle'] = isset($teamList[$v['team']]) ? $teamList[$v['team']] : '';
            $level[$v['level']]['adminList'][] = $v;
        }
        sort($level);
        return $level;
    }

    /**
     * 获取管理员列表
     */
    public function getAdminList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $adminIds = self::getAdminIds();
        $where['id'] = ['in', $adminIds];
        if (isset($params['keywords']))
        {
            $where['username|nickname|phone'] = ['LIKE', '%'.$params['keywords'].'%'];
        }
        if (isset($params['status']))
        {
            $where['status'] = ['eq', $params['status']];
        }
        if (isset($params['group']))
        {
            $groupAids = AuthModel::getInstance()->groupColumn([
                'group_id' => ['eq', $params['group']]
            ], 'uid');
            $groupAids = array_column($groupAids, 'uid');
            $where['id'] = ['in', $groupAids];
        }

        $total = AdminModel::getInstance()->count($where);
        $adminList = AdminModel::getInstance()->select($where, 'id,username,nickname,phone,team,pid,email,status,loginip,logintime,is_can_commission,is_open_product', $start, $limit);

        $adminIdArr = array_column($adminList, 'pid');
        $adminPid = AdminModel::getInstance()->column([
            'id' => ['in', $adminIdArr]
        ], 'username,nickname');

        $teams = TeamModel::getInstance()->column([
            'id' => ['in', array_column($adminList, 'team')]
        ], 'title,charge');

        $group = AuthModel::getInstance()->column([
            'aga.uid' => ['in', array_column($adminList, 'id')]
        ], 'ag.id, ag.name');
        $adminGroup = AuthModel::getInstance()->groupColumn([
            'uid' => ['in', array_column($adminList, 'id')]
        ], 'uid, group_id');

//        $total = in_array(1, array_column($adminList, 'id')) ? $total - 1 : $total;
        //岗位   上级  团队
        foreach ($adminList as $k => $v)
        {
            $adminList[$k]['parent'] = isset($adminPid[$v['pid']]) ? $adminPid[$v['pid']]['nickname'] : '';
            $adminList[$k]['teamTitle'] = isset($teams[$v['team']]) ? $teams[$v['team']]['title'] : '';
            $adminList[$k]['group'] = '';
            foreach ($group as $kk => $vv)
            {
                foreach ($adminGroup as $item)
                {
                    if ($item['uid'] == $v['id'] && $kk == $item['group_id'])
                    {
                        $adminList[$k]['group'] .= empty($adminList[$k]['group']) ? $vv : '、'.$vv;
                    }
                }
            }
            $adminList[$k]['logintime'] = empty($v['logintime']) ? '' : $this->stampToDateTime($v['logintime']);
            /*if ($v['id'] == 1)
            {
                unset($adminList[$k]);
            }*/
        }

        return [
            'total' => $total,
            'list' => array_values($adminList),
        ];
    }

    /**
     * 添加管理员
     */
    public function addAdmin($params)
    {
        $vData = [
            'username' => 'require',
            'nickname' => 'require',
            'group' => 'require',
            'pid' => 'require',
            'team' => 'require',
            'phone' => 'require',
            'email' => 'require|email',
            'status' => 'require',
            'is_can_commission' => 'require',
            'is_open_product' => 'require'
        ];
        if (empty($params['id']))
        {
            $vData['password'] = 'require';
            $vData['repeatPassword'] = 'require';
        }
        $Validate = new Validate($vData);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $salt = Random::alnum();

        $saveData = [
            'username' => $params['username'],
            'nickname' => $params['nickname'],
            'team' => $params['team'],
            'pid' => $params['pid'],
            'avatar' => isset($params['avatar']) ? $params['avatar'] : '',
            'phone' => $params['phone'],
            'email' => $params['email'],
            'status' => $params['status'],
            'is_open_product' => $params['is_open_product'],
            'is_can_commission' => $params['is_can_commission'],
            'level' => AdminModel::getInstance()->value([
                'id' => ['eq', $this->uid]
            ], 'level') + 1
        ];

        Db::startTrans();
        try{
            $group = explode(',', $params['group']);
            /*//过滤不允许的组别,避免越权
            $group = in_array(1, explode(',', $this->group_id)) ? $group : array_intersect(explode(',', $this->group_id), $group);
            print_r($group);die;
            if (!$group) {
                $this->error(__('The parent group exceeds permission limit'));
            }*/

            if (!empty($params['id']))
            {
                $saveData['updatetime'] = time();
                $res = AdminModel::getInstance()->update($params['id'], $saveData);
                if (!$res)
                {
                    $this->error('编辑失败');
                }
                $uid = $params['id'];
            }else{
                if ($params['password'] != $params['repeatPassword'])
                {
                    $this->error('两次密码不一致');
                }

                $saveData['salt'] = $salt;
                $saveData['password'] = md5(md5($params['password']) . $salt);
                $saveData['createtime'] = time();

                $adminInfo = AdminModel::getInstance()->value([
                    'username' => ['eq', $saveData['username']]
                ], 'id');
                if ($adminInfo)
                {
                    $this->error('登录账号重复');
                }

                $uid = AdminModel::getInstance()->insert($saveData);
                if (!$uid)
                {
                    $this->error('添加失败');
                }
            }

            $dataset = [];
            foreach ($group as $value) {
                $dataset[] = ['uid' => $uid, 'group_id' => $value];
            }
            AuthModel::getInstance()->delete([
                'uid' => ['eq', $uid]
            ]);
            AuthModel::getInstance()->saveAll($dataset);

            LogService::getInstance()->writeSysLog([
                'operation' => '/api/admin/changeAdmin',
                'title' => !empty($params['id']) ? '编辑' : '添加',
                'content' => $params,
            ]);

            Db::commit();
            return [
                'type' => true,
                'msg' => !empty($params['id']) ? '编辑成功' : '添加成功',
                'data' => [
                    'id' => $uid
                ]
            ];
        }catch (Exception $e)
        {
            Db::rollback();
            return [
                'type' => false,
                'msg' => $e->getMessage()
            ];
        }
    }

    /**
     * 修改账号密码
     */
    public function changePassword($params)
    {
        $Validate = new Validate([
            'id' => 'require',
            'password' => 'require',
            'repeatPassword' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        if ($params['password'] != $params['repeatPassword'])
        {
            $this->error('两次密码不一致');
        }
        $salt = Random::alnum();
        $saveData = [
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt
        ];
        LogService::getInstance()->writeSysLog([
            'operation' => '/api/admin/changePassword',
            'title' => '修改密码',
            'content' => $params,
        ]);
        return AdminModel::getInstance()->update($params['id'], $saveData);
    }

    /**
     * 获取可用管理员
     */
    public function getAdmin($params, $isThis = false)
    {
        $where = [];
        $adminIds = self::getAdminIds($isThis);
        $where['id'] = ['in', $adminIds];
        if (isset($params['keywords']))
        {
            $where['username|nickname|phone'] = ['LIKE', '%'.$params['keywords'].'%'];
        }
        $adminList = AdminModel::getInstance()->select($where, 'id,username,nickname,phone,status,team', 0, 100000);

        $group = AuthModel::getInstance()->column([
            'aga.uid' => ['in', array_column($adminList, 'id')]
        ], 'ag.id, ag.name');
        $adminGroup = AuthModel::getInstance()->groupColumn([
            'uid' => ['in', array_column($adminList, 'id')]
        ], 'uid, group_id');

        $teams = TeamModel::getInstance()->column([
            'id' => ['in', array_column($adminList, 'team')]
        ], 'title,charge');
        foreach ($adminList as $k => $v)
        {
            $adminList[$k]['teamTitle'] = isset($teams[$v['team']]) ? $teams[$v['team']]['title'] : '';
            $adminList[$k]['group'] = '';
            foreach ($group as $kk => $vv)
            {
                foreach ($adminGroup as $item)
                {
                    if ($item['uid'] == $v['id'] && $kk == $item['group_id'])
                    {
                        $adminList[$k]['group'] .= empty($adminList[$k]['group']) ? $vv : '、'.$vv;
                    }
                }
            }
        }

        return $adminList;
    }

    /**
     * 获取指定管理员信息
     */
    public function getAdminInfo($params)
    {
        $Validate = new Validate([
            'aid' => 'require'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $aInfo = AdminModel::getInstance()->find([
            'id' => ['eq', $params['aid']]
        ], 'id,username,nickname,phone,email,pid,team,status,is_can_commission,is_open_product');
        $groupIds = AuthModel::getInstance()->groupColumn([
            'uid' => ['eq', $params['aid']]
        ],'group_id');
        $groupIds = array_column($groupIds, 'group_id');
        $aInfo['group'] = $groupIds;
        $pName = AdminModel::getInstance()->value([
            'id' => ['eq', $aInfo['pid']]
        ], 'nickname');
        $aInfo['pName'] = empty($pName) ? '无' : $pName;
        $teamName = TeamModel::getInstance()->value([
            'id' => ['eq', $aInfo['team']]
        ], 'title');
        $aInfo['teamName'] = empty($teamName) ? '无' : $teamName;
        $groupName = Db::name('auth_group')->where([
            'id' => ['in', $groupIds]
        ])->column('name', 'id');
        $aInfo['groupName'] = empty($groupName) ? '无' : implode('、', $groupName);
        return $aInfo;
    }

    /**
     * 获取当前账号及其下属账号id
     */
    public function getAdminIds($isThis = false)
    {
        $where = !$isThis ? [
            'id' => ['neq', $this->uid]
        ] : [];
        $adminList = AdminModel::getInstance()->select($where, 'id,pid,username', 0, 100000);
        $adminTree = self::getAdminTree($adminList, $this->uid);
        $adminTree = $this->uid == 1 ? array_column($adminList, 'id') : $adminTree;
        if ($isThis)
        {
            $adminTree[] = $this->uid;
        }
        return $adminTree;
    }

    public function getAdminTree($data, $pid = 0)
    {
        $teamTree = [];
        foreach ($data as $k => $v)
        {
            if ($v['pid'] == $pid)
            {
                $teamTree[] = $v['id'];
                $child = self::getAdminTree($data, $v['id']);
                if (!empty($child))
                {
                    foreach ($child as $item)
                    {
                        $teamTree[] = $item;
                    }
                }
            }
        }
        return $teamTree;
    }
}